package com.gzcss.gulimall.product.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.gzcss.gulimall.product.vo.webVo.catalogL2Vo;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzcss.common.utils.PageUtils;
import com.gzcss.common.utils.Query;

import com.gzcss.gulimall.product.dao.CategoryDao;
import com.gzcss.gulimall.product.entity.CategoryEntity;
import com.gzcss.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationServiceImpl categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /*
     *   生产分类树形结构
     *   GGH
     * */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2、组装成父子树形结构
        List<CategoryEntity> Level1Menus = entities.stream().filter(CategoryEntity -> {
            return CategoryEntity.getParentCid() == 0;
        }).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {          //对组装好的菜单进行排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return Level1Menus;
    }

    /*
     *   GGH
     *   逻辑删除
     * */
    @Override
    public void gghRemoveMenuByid(List<Long> asList) {
        //TODO 1、检查当前菜单是否被其他地方引用
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 获取catelogId的完整路径
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parenPath = findParenPath(catelogId, paths);
        //将收集到的结果逆序
        Collections.reverse(parenPath);
        return parenPath.toArray(new Long[parenPath.size()]);
    }

    /**
     * 级联更新所有关联的数据M
     *
     * @param category
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);

        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

    }

    @Override
    public List<CategoryEntity> getLevel1Category() {
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntityList;
    }

    @Override
    public Map<String, List<catalogL2Vo>> getCatalogl2() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        //判断缓存中是否存在数据
        if (StringUtils.isEmpty(catalogJSON)) {
            //缓存不命中，从数据库查
            Map<String, List<catalogL2Vo>> catalogl2db = getCatalogJsonFromRedisLock();
            return catalogl2db;
        }
        //缓存命中，直接从缓存中返回
        log.info("缓存命中，直接返回结果");
        Map<String, List<catalogL2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<catalogL2Vo>>>() {
        });
        return result;
    }

    /**
     * 通过redis来实现分布式锁
     **/
    public Map<String, List<catalogL2Vo>> getCatalogJsonFromRedisLock() {
        String uuid= UUID.randomUUID().toString();
        //1、占用分布式锁，从Redis中占,加锁操作和设置超时时间必须是一个原子(同步)操作，避免出现死锁问题
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);
        //判断是否拿到锁
        if (lock) {
            /**
             1、抢占到锁，执行数据库查询
             2、执行完业务后，删除锁
             **/
            Map<String, List<catalogL2Vo>> dataFromDB = null;
            try {
                dataFromDB = getDataFromDB();
            }finally {
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"),uuid);
            }
            return dataFromDB;
        } else {
            log.info("没有抢占倒锁，继续抢占");
            /**没抢占到锁，采取自旋方式，继续获取锁**/
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromRedisLock();
        }

    }

    /**
     * 通过synchronized(this)实现本地锁
     **/
    public Map<String, List<catalogL2Vo>> getCatalogJsonFromLocalLock() {
        //加锁
        synchronized (this) {
            return getDataFromDB();
        }
    }

    /**
     * 从数据库中获取数据
     **/
    private Map<String, List<catalogL2Vo>> getDataFromDB() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        //判断缓存中是否存在数据
        if (!StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<catalogL2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<catalogL2Vo>>>() {
            });
            return result;
        }
        log.info("缓存不命中，查数据库");
        //查出所有数据
        List<CategoryEntity> entities = baseMapper.selectList(null);
        List<CategoryEntity> categoryEntityListL1 = getParent_cid(entities, 0L);
        //获取一级分类
        Map<String, List<catalogL2Vo>> getCatalogl2Map = categoryEntityListL1.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> catalogryl2 = getParent_cid(entities, v.getCatId());

            List<catalogL2Vo> catalogL2Vos = catalogryl2.stream().map(l2 -> {
                catalogL2Vo catalogL2Vo = new catalogL2Vo();
                catalogL2Vo.setCatalog1Id(v.getCatId().toString());
                catalogL2Vo.setId(l2.getCatId().toString());
                catalogL2Vo.setName(l2.getName());
                List<CategoryEntity> catalogl3 = getParent_cid(entities, l2.getCatId());
                List<catalogL2Vo.catalogL3Vo> catalogl3List = catalogl3.stream().map(l3 -> {
                    catalogL2Vo.catalogL3Vo catalogL3Vo = new catalogL2Vo.catalogL3Vo();
                    catalogL3Vo.setCatalog2Id(l2.getCatId().toString());
                    catalogL3Vo.setId(l3.getCatId().toString());
                    catalogL3Vo.setName(l3.getName());
                    return catalogL3Vo;
                }).collect(Collectors.toList());
                catalogL2Vo.setCatalog3List(catalogl3List);
                return catalogL2Vo;
            }).collect(Collectors.toList());
            return catalogL2Vos;
        }));
        //转成字符串保存到缓存(序列化)
        String s = JSON.toJSONString(getCatalogl2Map);
        log.info("存入redis");
        redisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);
        return getCatalogl2Map;
    }


    private List<CategoryEntity> getParent_cid(List<CategoryEntity> entities, Long v) {
        List<CategoryEntity> collect = entities.stream().filter(item -> item.getParentCid() == v).collect(Collectors.toList());
        //return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        return collect;
    }

    /**
     * 递归查找所有的父节点的id
     **/
    private List<Long> findParenPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParenPath(byId.getParentCid(), paths);
        }

        return paths;
    }

    /**
     * 递归查找所有菜单的子菜单
     **/
    private List<CategoryEntity>  getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map(categoryEntity -> {
            //1、找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //2、菜单的排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

}
